package com.gitee.limaozhi.socket.lesson03.example4;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author hzlimaozhi
 * @date 2019/08/08 09:23
 */
public class HttpResponse {

    private static final String LINE_END = "\r\n";

    private String version = "HTTP/1.1";

    private int code = 200;

    private String reason = "OK";

    private Map<String, String> headers = new LinkedHashMap<>();

    private String content;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public void setKeepAlive(boolean keepAlive) {
        headers.put("Connection", keepAlive ? "keep-alive" : "close");
    }

    public String raw() {
        StringBuilder sb = new StringBuilder();
        sb.append(version + " " + code + " " + reason + LINE_END);
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            sb.append(entry.getKey() + ": " + entry.getValue() + LINE_END);
        }
        if (content != null && content != "") {
            sb.append("Content-Type: text/html; charset=utf-8" + LINE_END);
            sb.append("Content-Length: " + content.getBytes().length + LINE_END);
            sb.append(LINE_END);
            sb.append(content);
        } else {
            sb.append(LINE_END);
        }

        return sb.toString();
    }

}
